<template>
  <CollapseContainer title="扩展配置" :canExpan="false">
    <Alert
      message="扩展配置为系统业务所有的配置，应该由系统管理员操作，如需用户配置应另起业务配置页面。"
      type="warning"
      closable
      @close="onClose"
      style="margin-bottom: 10px"
    />
    <a-button type="primary" style="margin-bottom: 8px" @click="handleAdd">添加配置</a-button>
    <BasicTable @register="registerTable" @edit-change="onEditChange">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction :actions="createActions(record, column)" />
        </template>
      </template>
    </BasicTable>
  </CollapseContainer>
</template>
<script lang="ts">
  import { Alert } from 'ant-design-vue';
  import { defineComponent, ref, inject } from 'vue';
  import {
    BasicTable,
    useTable,
    TableAction,
    BasicColumn,
    ActionItem,
    EditRecordRow,
  } from '@/components/Table';
  import { cloneDeep } from 'lodash-es';
  import { columns } from './data';
  import { getSettingList, createSetting, updateSetting, deleteSetting } from '@/api/app/setting';
  import { useMessage } from '@/hooks/web/useMessage';
  import { CollapseContainer } from '@/components/Container/index';

  export default defineComponent({
    name: 'SystemSettingManagement',
    components: { BasicTable, TableAction, CollapseContainer, Alert },
    setup() {
      const { createMessage: msg } = useMessage();
      const currentEditKeyRef = ref('');
      const tab_id: any = inject('tab_id');
      const [
        registerTable,
        { reload, getDataSource, insertTableDataRecord, deleteTableDataRecord },
      ] = useTable({
        api: getSettingList,
        beforeFetch: (res) => {
          res.tab_id = tab_id.value;
          return res;
        },
        columns: columns,
        // rowKey: 'key',
        showIndexColumn: true,
        showTableSetting: false,
        tableSetting: { fullScreen: false },
        bordered: true,
        actionColumn: {
          width: 160,
          title: '操作',
          dataIndex: 'action',
        },
      });

      function createActions(record: EditRecordRow, column: BasicColumn): ActionItem[] {
        if (!record.editable) {
          return [
            {
              label: '编辑',
              disabled: currentEditKeyRef.value ? currentEditKeyRef.value !== record.key : false,
              onClick: handleEdit.bind(null, record),
            },
            {
              label: '删除',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                confirm: handleDelete.bind(null, record),
              },
            },
          ];
        }
        return [
          {
            label: '保存',
            onClick: handleSave.bind(null, record, column),
          },
          {
            label: '取消',
            color: 'warning',
            onClick: handleCancel.bind(null, record),
          },
        ];
      }

      // 监听表单变化
      function onEditChange({ column, value, record }) {
        // 本例
        if (column.dataIndex === 'id') {
          record.editValueRefs.name4.value = `${value}`;
        }
        // console.log(column, value, record);
      }

      // 添加配置
      const handleAdd = async () => {
        const newData = {
          id: 0,
          title: '',
          menu_name: '',
          value: '',
          sort: 0,
          status: 1,
          remarks: '',
          key: getDataSource().length + 1,
        };
        const insertTab: any = await insertTableDataRecord(newData);
        await insertTab[insertTab.length - 1].onEdit?.(true);
      };

      // 处理编辑
      function handleEdit(record: EditRecordRow) {
        currentEditKeyRef.value = record.key;
        record.onEdit?.(true);
      }

      // 取消处理
      function handleCancel(record: EditRecordRow) {
        currentEditKeyRef.value = '';
        record.onEdit?.(false, false);
      }

      // 删除处理
      function handleDelete(record: EditRecordRow) {
        if (record.id) {
          deleteSetting(record.id).then(() => {
            msg.success('删除成功');
            reload();
          });
        } else {
          deleteTableDataRecord(record.key);
          record.onEdit?.(false, false);
        }
      }

      // 保存配置处理
      async function handleSave(record: EditRecordRow) {
        // 校验
        msg.loading({ content: '正在保存...', duration: 0, key: 'saving' });
        const valid = await record.onValid?.();
        if (valid) {
          try {
            const data = cloneDeep(record.editValueRefs);
            const newObject: any = { config_tab_id: tab_id.value };
            const merged = Object.assign({}, data, newObject);
            //TODO 此处将数据提交给服务器保存

            // 判断是否存在主键更新
            if (record.id) {
              // 更新配置数据
              await updateSetting(record.id, merged);
            } else {
              // 创建配置数据
              await createSetting(merged);
            }

            // 保存之后提交编辑状态
            const pass = await record.onEdit?.(false, true);
            if (pass) {
              currentEditKeyRef.value = '';
            }
            msg.success({ content: '数据已保存', key: 'saving' });
            reload();
          } catch (error) {
            msg.error({ content: '保存失败', key: 'saving' });
          }
        } else {
          msg.error({ content: '请填写正确的数据', key: 'saving' });
        }
      }

      // 关闭提示消息
      const onClose = () => {};

      return {
        registerTable,
        handleEdit,
        createActions,
        onEditChange,
        handleAdd,
        onClose,
      };
    },
  });
</script>
<style lang="less" scoped>
  ::v-deep .vben-page-wrapper-content {
    margin: 0;
  }

  ::v-deep .ant-table-wrapper {
    padding: 0;
  }
</style>
./base/data